package cn.edu.hfut.dmic.webcollector.net;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Random;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Proxys extends ArrayList<Proxy> {
	private static final long serialVersionUID = 1L;

	public static final Logger LOG = LoggerFactory.getLogger(Proxys.class);

	public static Random random = new Random();

	public void add(String ip, int port) {
		Proxy proxy = new Proxy(Proxy.Type.HTTP,
				new InetSocketAddress(ip, port));
		this.add(proxy);
	}

	public void add(String proxyStr) throws Exception {
		try {
			String[] infos = proxyStr.split(":");
			String ip = infos[0];
			int port = Integer.valueOf(infos[1]);

			Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(ip,port));
			this.add(proxy);
		} catch (Exception ex) {
			LOG.info("Exception", ex);
		}

	}

	public Proxy nextProxy() {
		return getRandomProxy();
	}

	public Proxy getRandomProxy() {

		if (this.isEmpty()) {
			return null;
		}
		try {
			int r = random.nextInt(this.size());
			return this.get(r);
		} catch (Exception ex) {
			return null;
		}
	}

	/**
	 * 添加代理列表（同时去除重复）
	 * 
	 * @param file
	 * @throws Exception
	 */
	public void addAllFromFile(File file) throws Exception {
		FileInputStream fis = new FileInputStream(file);
		BufferedReader br = new BufferedReader(new InputStreamReader(fis));
		Set<String> linesSet = new HashSet<String>();
		String line = null;
		while ((line = br.readLine()) != null) {
			line = line.trim();
			if (line.startsWith("#") || line.isEmpty()) {
				continue;
			} else {
				linesSet.add(line);
			}
		}
		if (linesSet.size() > 0) {
			Iterator<String> itea = linesSet.iterator();
			while (itea.hasNext()) {
				this.add(itea.next());
			}
			LOG.info("共有代理IP:" + this.size() + "个");
		}
	}

	public Proxys removeSameItem(Proxys proxys) {
		Set<Proxy> linkSet = new LinkedHashSet<Proxy>();
		linkSet.addAll(proxys);
		proxys.clear();
		proxys.addAll(linkSet);
		return proxys;
	}

}
